#!/bin/sh

PORT=8080
CONFIG=$HOME/.config/rsync/rsync.conf
CACHE_DIR=$HOME/.cache/rsyncd
OPT_HTTP=false

IP=$(ip addr | awk '/state UP/ {getline; getline; $0=$2; gsub(/\/.*/, "");print; exit}')

usage () {
	cat <<EOF>&2
Usage: ${0##*/} PATH

Share PATH over the network.

By default, startup an rsync daemon and share PATH as read-only under the
'files' module.  Clients can sync with, for instance:

  rsync -iavzzP rsync://$IP:$PORT/files DESTINATION

An HTTP server can be started instead.

Options:

  -p PORT: Specify a port number (default: $PORT).
           Must be above 1024 to run without privileges.

  -H:      Start an HTTP server instead.

EOF
}

while getopts ":hHp:" opt; do
	case $opt in
	h)
		usage
		exit ;;
	H)
		OPT_HTTP=true ;;
	p)
		PORT="$OPTARG" ;;
	\?)
		usage
		exit 1 ;;
	esac
done

shift $(($OPTIND - 1))

[ $# -ne 1 ] && usage && exit 1
[ "$1" = "-h" ] && usage && exit
[ "$1" = "--" ] && shift


TARGET=$(realpath "$1")

share_rsync(){
	mkdir -p "$(dirname "$CONFIG")" "$CACHE_DIR"
	cat<<EOF>"$CONFIG"
pid file = $CACHE_DIR/rsyncd.pid
lock file = $CACHE_DIR/rsyncd.lock
log file = $CACHE_DIR/rsyncd.log
port = $PORT
use chroot = false

[files]
path = $TARGET
comment = Rsync share
read only = true
timeout = 300

EOF

	rsync --daemon --config="$CONFIG" && \
		echo >&2 "rsync daemon listening on $IP:$PORT"
}

share_woof() {
	if command -v guix >/dev/null 2>&1; then
		guix environment -C -N --expose="$TARGET"="$TARGET" --ad-hoc woof -- woof -c 9999 -p $PORT "$TARGET" || \
			guix environment --ad-hoc woof -- woof -c 9999 -p $PORT "$TARGET"
	else
		woof -c 9999 -p $PORT "$TARGET"
	fi
}

share_python() {
	echo >&2 "Python HTTP server will listen on $IP:$PORT."
	if command -v guix >/dev/null 2>&1; then
		guix environment -C -N --expose="$TARGET"="$TARGET" --ad-hoc python -- \
			python3 -m http.server -d "$TARGET" $PORT
	elif command -v python3 >/dev/null 2>&1; then
		python3 -m http.server -d "$TARGET" $PORT
	else
		python -m http.server -d "$TARGET" $PORT
	fi
}

if [ -f "$TARGET" ]; then
	share_woof "$TARGET"
elif $OPT_HTTP; then
	share_python "$TARGET"
else
	share_rsync
fi
